/**
 * @Time: 2018/11/22 10:22
 * @Author: wangmin
 * @File: httpjson
 * @Software: GoLand
 */
package httpjson

import (
	"../encryption"
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

// json格式的网络请求
func Request(url string, data interface{}, encrypt bool, key []byte, iv []byte) (error, []byte) {
	client := &http.Client{
		Timeout: time.Second * 5,
	}
	dataB, err := json.Marshal(data)
	if err != nil {
		return err, []byte{}
	}
	var dataR io.Reader
	if encrypt {
		dataS, err := encryption.AesEncrypt(string(dataB), key, iv)
		if err != nil {
			return err, []byte{}
		}
		dataR = strings.NewReader(dataS)
	} else {
		dataR = bytes.NewReader(dataB)
	}
	req, err := http.NewRequest("POST", url, dataR)
	if err != nil {
		return err, []byte{}
	}
	req.Header.Add("Content-Type", "application/json")
	resp, err := client.Do(req)
	if err != nil {
		return err, []byte{}
	}
	rb, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err, []byte{}
	}
	if encrypt {
		rbe, err := encryption.AesDecrypt(string(rb), key, iv)
		if err != nil {
			return err, []byte{}
		}
		return nil, rbe
	}
	return nil, rb
}
